package cn.orangeframe.neon.application.mapper;

import cn.orangeframe.neon.application.exception.TerminateWorkflowException;
import cn.orangeframe.neon.domain.entity.WorkflowTask;
import cn.orangeframe.neon.domain.enums.TaskStatus;
import cn.orangeframe.neon.domain.enums.TaskType;
import cn.orangeframe.neon.domain.model.TaskModel;
import cn.orangeframe.neon.domain.model.WorkflowModel;
import org.springframework.stereotype.Component;

import java.util.List;

@Component(TaskType.TASK_TYPE_DO_WHILE)
public class DoWhileTaskMapper implements TaskMapper {

    @Override
    public String getTaskType() {
        return TaskType.TASK_TYPE_DO_WHILE;
    }

    @Override
    public List<TaskModel> getMappedTasks(TaskMapperContext taskMapperContext) throws TerminateWorkflowException {
        WorkflowTask workflowTask = taskMapperContext.getTaskToSchedule();
        WorkflowModel workflowModel = taskMapperContext.getWorkflowInstance();

        TaskModel task = workflowModel.getTaskByRefName(workflowTask.getTaskReferenceName());
        if (task != null && task.getStatus().isTerminal()) {
            // Since loopTask is already completed no need to schedule task again.
            return List.of();
        }

        TaskModel doWhileTask = taskMapperContext.createTaskModel();
        doWhileTask.setTaskType(TaskType.TASK_TYPE_DO_WHILE);
        doWhileTask.setStatus(TaskStatus.IN_PROGRESS);
        doWhileTask.setStartTime(System.currentTimeMillis());
        doWhileTask.setRetryCount(taskMapperContext.getRetryCount());
        return List.of(doWhileTask);
    }
}
